import Toast from '@vant/weapp/toast/toast'
import { hasValue, parseURLParams } from '../../utils/util'
import { fetchPlayerList, bindPlayer, upPlayer, checkLogin } from '../../api/index'

function getUniquePlayerNames(playerList: any[], statsOne: string, statsTwo: string): { text: string; value: string }[] {
  // 使用 Set 来存储 statsOne 的唯一值
  const uniqueNames = new Set<string>();
  playerList.forEach((player) => {
    uniqueNames.add(player[statsOne]);
  });

  // 使用 Map 来存储 statsOne 和对应的 statsTwo
  const nameScoreMap = new Map<string, string>();
  uniqueNames.forEach((name) => {
    const playersWithSameName = playerList.filter((p) => p[statsOne] === name);
    if (playersWithSameName.length > 0) {
      // 选择第一个匹配的 player 的 statsTwo 的值
      const firstMatch = playersWithSameName[0];
      // 确保 statsTwo 的值总是存在
      const score = firstMatch[statsTwo] || 'default_value'; // 替换 'default_value' 为实际的默认值
      nameScoreMap.set(name, score);
    }
  });

  // 遍历 Map，确保每个唯一的 statsOne 值只返回一个有效的 statsTwo 值
  const result = [];
  nameScoreMap.forEach((score, name) => {
    if (score !== 'default_value') { // 如果 score 不是默认值，则添加到结果中
      result.push({ text: name, value: score });
    }
  });

  // 返回结果
  return result;
}
Component({
  data: {
    topImage: 'https://bd.yiquhz.com/bg/ff3081.jpg',
    showCode: false,
    playerList: [],
    userIdList: [],
    GameList: [],
    RoleList: [],
    formPlayer: {
      userId: '',
      partitionId: '',
      gameName: '',
      roleName: '',
      wechatName: '',
      openId: ''
    },
    securityCode: '',
    showGetCode: true,
    PlayerInfo: {
      playerId: '',
      playerName: '',
      openId: '',
      showCode: ''
    },
    showLogin: false,
    showBtn: false,
    showDialog: false,
    beforeClose(action) {
      return new Promise(resolve => {
        if (action === 'confirm') {
          resolve(false);
        } else {
          resolve(true);
        }
      });
    }
  },
  methods: {
    onLoad: function (options: any) {
      this.setData({ "formPlayer.userId": '' })
      //false 登录 true获取数据
      if (options.q) { //扫码进入
        const qrUrl = decodeURIComponent(options.q)
        // 解析URL参数
        const params = parseURLParams(qrUrl);
        //没有登录
        const openid = checkLogin();
        openid.then(item => {
          if (item) {
            //打开登录，获取玩家信息
            wx.setStorageSync('openId', item)
            this.setData({
              "formPlayer.openId": item,
              "formPlayer.userId": params.playerName,
              "formPlayer.partitionId": params.partitionId,
              "formPlayer.gameName": params.gamePartition,
              "formPlayer.roleName": params.roleName,
              showLogin: true
            })
          }
        })
      } else {
        //非扫码登录不执行绑定
        // 判断是否已经登录
        if (hasValue(wx.getStorageSync("openId"))) {
          this.getPlayerList(wx.getStorageSync("openId"))
        } else {
          //没有登录
          const openid = checkLogin();
          openid.then(item => {
            if (item) {
              wx.setStorageSync('openId', item)
              this.setData({ showLogin: true, "formPlayer.openId": item })
            }
          })
        }
      }

    },
    closeLogin() {
      this.setData({ showLogin: true })
    },
    //确定登录
    onLogin() {
      if (wx.getStorageSync('wechatName').length > 0) {
        this.setData({
          "formPlayer.wechatName": wx.getStorageSync('wechatName'),
          "formPlayer.openId": wx.getStorageSync("openId")
        });
        // this.getPlayerList(this.data.formPlayer.openId)
        //只有扫码进入才需要新增
        //进行绑定
        if (this.data.formPlayer.userId.length > 0) {
          this.bindPlayerF(this.data.formPlayer)
        }
        // 关闭模态对话框
        this.setData({ showLogin: false });
      } else {
        //提示需要先登录
        wx.showToast({
          title: '请先输入昵称！',
          icon: 'none',
          duration: 2000
        });
      }
    },
    //获取用户游戏信息
    getPlayerList: async function (openId: string) {
      try {
        const playerList = await fetchPlayerList(openId, false);
        if (playerList == null) {
          wx.redirectTo({ url: "/pages/error/error" });
          return
        }
        // 使用 map 函数将 playerList 中的属性转换为所需格式
        const userIdList = getUniquePlayerNames(playerList, "playerName", "playerName");
        wx.setStorageSync('openId', openId)
        wx.setStorageSync('wechatName', playerList[0].wechatName)
        // 筛选出特定游戏的玩家
      const filteredPlayers = playerList.filter(player => player.playerName === playerList[0].playerName);
      const GameList = getUniquePlayerNames(filteredPlayers, "gamePartition", "partitionId");
        this.setData({
          userIdList: userIdList,
          playerList: playerList,
          "formPlayer.wechatName": playerList[0].wechatName,
          "formPlayer.openId": playerList[0].openId,
          "formPlayer.userId": playerList[0].playerName,
          "formPlayer.gameName": playerList[0].partitionId,
          GameList: GameList,
          "formPlayer.roleName": playerList[0].roleName,
          RoleList: [{ text: playerList[0].roleName, value: playerList[0].roleName }]
        })
        if(playerList[0].showCode){
          this.setData({
            showCode:true,
             securityCode: playerList[0].securityCode
          })
        }
      } catch (err) {
        console.log(err)
        wx.redirectTo({ url: "/pages/empty/empty" });
      }
    },
    bindPlayerF: async function (palyerData: object) {
      try {
        const palyer = await bindPlayer(palyerData);
        wx.showToast({
          title: palyer,
          icon: 'none',
          duration: 2000
        });
        //获取最新数据
        this.setData({
          "formPlayer.userId": '', "formPlayer.roleName": '', "formPlayer.partitionId": ''
          , "formPlayer.gameName": ''
        })
        this.getPlayerList(this.data.formPlayer.openId)
      } catch (err) {
        console.log("错误")
      }
    },
    // 游戏账号
    onUserChange(e: any) {
      // 筛选出特定游戏的玩家
      const filteredPlayers = this.data.playerList.filter(player => player.playerName === e.detail);
      const GameList = getUniquePlayerNames(filteredPlayers, "gamePartition", "partitionId");
      this.setData({
        "formPlayer.userId": e.detail,
        GameList: GameList,
        "formPlayer.gameName":'',
        "formPlayer.roleName":'',
        showCode:false
      })
    },
    //游戏分区
    onGameChange(e: any) {
      // 筛选出特定游戏的玩家
      const filteredPlayers = this.data.playerList.filter(player => player.partitionId === e.detail
        && player.playerName === this.data.formPlayer.userId);
      // 提取出这些玩家的 role 列表
      const roleListForGame = filteredPlayers.map(player => ({
        text: player.roleName,
        value: player.roleName
      }));
      this.setData({
        RoleList: roleListForGame,
        "formPlayer.gameName": e.detail,
        showCode:false
      })
    },
    //角色信息
    onRoleChange(e: any) {
      const playerName = this.data.playerList.find(player =>
        player.playerName === this.data.formPlayer.userId &&
        player.partitionId === this.data.formPlayer.gameName &&
        player.roleName === e.detail
      );
      this.setData({
        "formPlayer.roleName": e.detail,
        securityCode: playerName.securityCode,
        wechatName: playerName.wechatName,
        showCode: playerName.showCode,
        PlayerInfo: {
          playerId: playerName.playerId,
          playerName: playerName.playerName,
          openId: playerName.openId,
          showCode: playerName.showCode
        }
      })
    },

    // 关闭安全码
    closeCode: function () {
      wx.showModal({
        title: '提示',
        content: '关闭安全码可能导致账号被盗，造成的损失需自行承担。',
        success: (res) => { // 使用箭头函数
          if (res.confirm) {
            this.upPlayerF(false);
          } else if (res.cancel) {
            // 用户点击取消
          }
        }
      });
    },
    //开启安全码
    openCode() {
      if (this.data.formPlayer.roleName) {
        this.upPlayerF(true)
      } else {
        Toast('请先选择账号角色信息');
      }
    },
    upPlayerF: async function (codeTip: boolean) {
      this.setData({
        showCode: codeTip,
        'PlayerInfo.showCode': codeTip,
      });
      try {
        const palyer = await upPlayer(this.data.PlayerInfo);
        if (palyer !== 0) {
          this.setData({
            showCode: !codeTip,
            'PlayerInfo.showCode': !codeTip,
          });
          wx.showToast({
            title: '系统错误，请稍后再试',
            icon: 'none',
            duration: 2000
          });
        }
      } catch (err) {
        wx.showToast({
          title: '系统错误，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      }
    },
    copyInfo() {
      wx.setClipboardData({
        data: this.data.securityCode,
        success() {
          wx.showToast({
            title: '复制成功',
          })
        }
      })
    }
  }

})
